//
//  SearchNumVC.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/16/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

protocol SearchNumVCDelegate : class {
    
    func selectTheRecord(record : Record)
}


class SearchNumVC: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
  
    @IBOutlet weak var toTopSpace: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    var searchController : UISearchController!
    var resultVC : ResultVC!
    var bgImageView = UIImageView()
    var searchBar : UISearchBar!
    var records : [Record] = [Record]()
    var resultArray : [Record] = [Record]()
    var isSearching : Bool = false
    weak var delegate : SearchNumVCDelegate?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()

        
        
        setNavBarStyle(.transparency)
    
        setup()
        setupSearchController()
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        
        super.viewDidDisappear(animated)
        
        WRNavigationBar.defaultNavBarBarTintColor = UIColor.white
    }
}

extension SearchNumVC {
    
    func setup(){
        
        
        if #available(iOS 11.0, *) {
           
            self.toTopSpace.constant = CGFloat(kNavigationBarHeight + 16)
            
        } else {
            self.toTopSpace.constant = CGFloat(kNavigationBarHeight)
        }
        
    
        self.bgImageView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 100)
        
        self.bgImageView.image = UIImage(named: "navBackground")
        self.view.insertSubview(self.bgImageView, belowSubview: self.tableView)
        
        self.tableView.register(UINib(nibName: "SearchNumCell", bundle: nil), forCellReuseIdentifier: "SearchNumCell")
        
      
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        self.tableView.estimatedRowHeight = 44
        self.tableView.rowHeight = UITableView.automaticDimension
        
    }
    
    
    func setupSearchController(){
        
        //创建 搜索使用的表示图控制器
//        resultVC = ResultVC()
//
//        self.searchController = UISearchController(searchResultsController:nil)
//        searchController.searchResultsUpdater = self
//        searchController.delegate = self
//        searchController.searchBar.delegate = self
//        searchController.dimsBackgroundDuringPresentation = false
//        searchController.hidesNavigationBarDuringPresentation = false
//        searchController.searchBar.frame = CGRect(x:0, y: 20, width: kScreenWidth, height: 44)
//        searchController.searchBar.showsCancelButton = true
//        searchController.searchBar.placeholder = "请输入作品名称/官方编号"
//
//        searchController.searchBar.searchBarStyle = UISearchBar.Style.default
//        searchController.searchBar.barTintColor = UIColor.white
//        searchController.searchBar.tintColor = UIColor.white
//
//        searchController.searchBar.sizeToFit()
//
////        let searchBg = UIColor.getImage(color: UIColor.white.withAlphaComponent(0.3), size:CGSize(width: kScreenWidth, height: 32))
//
////        searchController.searchBar.backgroundImage = searchBg
//        searchController.searchBar.backgroundColor = UIColor.clear
//        searchController.searchBar.setSearchFieldBackgroundImage(searchBg, for: UIControlState.normal)
        
        searchBar = UISearchBar(frame: CGRect(x: 0, y:kNavigationBarHeight - 44, width: kScreenWidth - 60 , height: 44))
        searchBar.searchBarStyle = UISearchBar.Style.default
        searchBar.backgroundColor = UIColor.clear
       
        searchBar.barTintColor = UIColor.clear
//        searchBar.barTintColor
        searchBar.setBackgroundImage(UIImage(), for: UIBarPosition.any, barMetrics: .default)
        
        searchBar.sizeToFit()
        searchBar.delegate = self
       searchBar.tintColor = UIColor.white
       searchBar.setImage(UIImage(named: "clear_placeholder"), for: UISearchBar.Icon.clear, state: UIControl.State.normal)
       searchBar.setImage(UIImage(named: "clear_placeholder"), for: UISearchBar.Icon.clear, state: .highlighted)
        
        searchBar.placeholder = LocalizedString("input_search_id_tips")
        searchBar.backgroundColor = UIColor.clear
        
        if let searchTextFiled = searchBar.value(forKey: "searchField") as? UITextField {
          
            searchTextFiled.tintColor = UIColor.white
            searchTextFiled.textColor = UIColor.white
            searchTextFiled.font = UIFont.systemFont(ofSize: 14)
            searchTextFiled.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
            searchTextFiled.layer.cornerRadius = 3.0
            searchTextFiled.clipsToBounds = true
            searchTextFiled.backgroundColor = UIColor.white.withAlphaComponent(0.3)
            searchTextFiled.clearButtonMode = .whileEditing
            if let image = UIImage(named: "searchIcon"){
                
                let iconView = UIImageView(image: image)
                iconView.frame = CGRect(x: 0, y: 0, width: 16, height: 16)
                searchTextFiled.leftView = iconView

        }
        }
    
//        self.navigationItem.titleView = searchBar
        self.navigationController?.navigationBar.isHidden = true
        
        self.view.addSubview(searchBar)
    
        let cancelBtn = UIButton()
        cancelBtn.setTitle(LocalizedString("cancel"), for: UIControl.State.normal)
        cancelBtn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        cancelBtn.addTarget(self, action: #selector(goBack), for: UIControl.Event.touchUpInside)
        self.view.addSubview(cancelBtn)
        
        cancelBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.searchBar.snp.right)
            make.right.equalTo(self.view.snp.right).offset(-5)
            make.top.bottom.equalTo(self.searchBar)
        }
        
        if let view = searchBar.subviews.safeObjectAtIndex(0){
            view.subviews.safeObjectAtIndex(0)?.removeFromSuperview()
        }
//
//    let contentView = searchBar.subviews[0]
//
//        for cc in contentView.subviews {
//
//            if cc .isKind(of: UIButton.self) {
//
//                 let btn = cc as! UIButton
//
//                btn.setTitle("取消", for: UIControl.State.normal)
//                btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
//                btn.isEnabled = true
//            }
//        }
    }
    
}



extension SearchNumVC {
    
    
    func getRecordsWithMactch(searchStr : String){
        
        let predicate = NSPredicate(format: "SELF  CONTAINS[cd] %@",searchStr)
        
        let arr  = self.records.filter({ record in
            
            guard let num = record.keywords else {return false}
            
            let flag = predicate.evaluate(with: num)
            return  flag })
        
        self.resultArray = arr
        
    }
    

    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        
        if ((searchBar.text?.count ?? 0) > 0) {
            
            searchBar.placeholder = "";
        }
    }
    
    
//    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
//
//
////        searchBar.placeholder = "请输入作品名称/官方编号"
////        self.isSearching = false
////        self.tableView.reloadData()
//    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        
       
        if searchText.count > 0 {
            
            self.getRecordsWithMactch(searchStr: searchText)
            //            self.resultVC.tableView.reloadData()
            self.isSearching = true
            self.tableView.reloadData()
        }else{
            searchBar
                .placeholder = LocalizedString("input_search_id_tips")
            self.isSearching = false
            self.tableView.reloadData()
        }
    }
//    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//
//        searchBar.endEditing(true)
//
//    }
    
    
    @objc func goBack(){
    
        self.dismiss(animated: true, completion: nil)
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if isSearching {
            return resultArray.count
        }
        return records.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "SearchNumCell") as? SearchNumCell else {
            return SearchNumCell()
        }
        
        var record = Record()
//
        if isSearching {
            record = self.resultArray[indexPath.row]
        }else {
            record = self.records[indexPath.row]
        }
        
//        record = self.records[indexPath.row]
        cell.configData(record: record)
    
        
        return  cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        print("-----点我了")
        var record : Record?

        if isSearching {
            record = self.resultArray[indexPath.row]
//            self.dismiss(animated: false, completion: nil)
        }else {
            record = self.records[indexPath.row]
        }
//
//         record = self.records[indexPath.row]
        if let model = record {
            
            self.dismiss(animated: false, completion: nil)
            self.delegate?.selectTheRecord(record: model)
           
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        searchBar.endEditing(true)
    }

    

//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        
//        return 80
//    }
    
    
   
    
}
